// pages/activedetial/activedetial.js
var WxParse = require("../../wxParse/wxParse.js");
var api = require("../../api.js"),
  app = getApp();
var r;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    detial_activity: {},
    partner: {},
    enrolls: [],
    consultes: [],
    active_title: "",
    pageIndex: 2,
    textNodes: '',
  },
  /**
   * 生命周期函数--监听页面加载
   *
   */
  onLoad: function(options) {
    r = this;
    var id = options.id;
    r.setData({
      id: id,
      sys: app.globalData.systeminfo
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this;
    r.toast = _this.selectComponent("#toast");
    var openid = getApp().globalData.wxUserInfo.openId;
    if (openid) {
      wx.showLoading({
        title: "数据加载中"
      });
      const first = new Promise((resolve, reject) => {
        var n = new Object();
        n.wsId = _this.data.id,
          n.openId = getApp().globalData.wxUserInfo.openId;
        wx.request({
          url: api.audio.workShopDetail,
          data: n,
          success: function(res) {
            var nodes = '';
            if (res.data.data.purchaseStatus == 1) {
              nodes = '已报名'
            } else {
              if (res.data.data.wsStatus != 2) {
                nodes = '点击报名'
              } else {
                nodes = '已结束'
              }
            }
            _this.setData({
              detial_activity: res.data.data,
              isCollection: res.data.data.isCollection,
              textNodes: nodes
            });
            resolve(200);
            WxParse.wxParse("activityDescription", "html", _this.data.detial_activity.wsDetail, _this, 5);
          }
        });
      });
      first.then(res => {
        Promise.all([_this.getPartner(), _this.getEnrolls(), _this.getRecommendData()]).then(data => {
          setTimeout(() => {
            wx.hideLoading();
          }, 1000);
        }).catch(res => {})
      });

    } else {
      app.globalData.type = 3;
      app.globalData.userId = r.data.id;
      wx.reLaunch({
        url: `/pages/welcome/welcome`
      })
    }
  },


  getDetails: function(e) {
    console.log(e)
    var t = new Object();
    const parOpenId = e.currentTarget.dataset.id;
    t.parOpenId = parOpenId,
      t.openId = getApp().globalData.wxUserInfo.openId;
    app.getData.skipToTeaDetail(t).then(res => {
      if (res.code == 200) {
        const data = res.data;
        setTimeout(() => {
          wx.navigateTo({
            url: `../audiodetail/audiodetail?id=${data.copId}`
          });
        }, 800);
      }
    })

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    console.log(res)
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1]
    if (res.from === 'button') {
      return {
        title: r.data.detial_activity.wsTitle,
        path: `/pages/discover/discover?id=${r.data.id}&shareType=3`,
        success: function(res) {
          // 转发成功
          console.log("转发成功:" + JSON.stringify(res));
        },
        fail: function(res) {
          // 转发失败
          console.log("转发失败:" + JSON.stringify(res));
        }
      }
    }
  },
  getPartner() {
    const that = this;
    const p = new Promise((resolve, reject) => {
      // 获取作者信息
      var m = new Object();
      (m.openId = that.data.detial_activity.openId);
      wx.request({
        url: api.art.partnerByOpenId,
        data: m,
        success: function(res) {
          if (res.statusCode == 200) {
            if (res.data.code == 200) {
              that.setData({
                partner: res.data.data,
              });
              resolve(res);
              WxParse.wxParse("article", "html", that.data.partner.partnerDesc, that, 5);
            }
          }
        }
      });
    });
    return p;

  },
  getEnrolls() {
    const that = this;
    const p = new Promise((resolve, reject) => {
      // 报名人员
      var a = new Object()
      a.otherId = that.data.id,
        a.pageIndex = 1,
        a.pageSize = 10
      a.type = 4,
        wx.request({
          url: api.audio.enrolls,
          data: a,
          success: function(res) {
            // console.log(res.data);
            if (res.statusCode == 200) {
              if (res.data.code == 200) {
                var people = [];
                // console.log(res)
                const arr = res.data.data;
                if (arr.lenth > 0) {
                  if (arr.length > 0 && arr.length <= 6) {
                    people = arr;
                  } else {
                    people = arr.slice(0, 6);
                  }
                }
                that.setData({
                  enrolls: people
                });
                resolve(res);
              }

            }
          }
        });
    });
    return p;
  },
  getRecommendData() {
    const that = this;
    const p = new Promise((resolve, reject) => {
      wx.request({
        url: api.audio.recommendDatas,
        data: {
          wsId: that.data.detial_activity.wsId
        },
        success: function(data) {
          if (data.statusCode == 200) {
            if (data.data.code == 200) {
              var arr = [];
              data.data.data.length > 0 ? arr = data.data.data : arr = [];
              that.setData({
                classData: arr,
              });
              resolve(data);
            }
          }
        }
      })
    });
    return p;

  },
  showModal: function() {
    var that = this;
    if (that.data.detial_activity.purchaseStatus == 1) {
      return;
    } else {
      if (that.data.detial_activity.wsStatus == 2) {
        return;
      } else {
        wx.showModal({
          title: '提示',
          content: '确定要报名吗',
          success: function(res) {
            if (res.confirm) {
              var t = new Object();
              t.openId = getApp().globalData.wxUserInfo.openId,
                t.wsId = that.data.id
              wx.request({
                url: api.audio.addRecommendOrder,
                data: t,
                method: "POST",
                header: {
                  "content-type": "application/x-www-form-urlencoded"
                },
                success(res) {
                  if (res.statusCode == 200) {
                    if (res.data.code == 200) {
                      wx.showToast({
                        title: '报名成功',
                        duration: 1000,
                        icon: 'success'
                      });
                      setTimeout(() => {
                        that.onShow();
                      }, 500)
                      // var pages = getCurrentPages();//获取页面栈
                      //   if (pages.length > 1) {
                      //   //上一个页面实例对象
                      //   var prePage = pages[pages.length - 2];
                      //   //调用上一个页面的onShow方法
                      //   prePage.onLoad();
                      //   wx.navigateBack({
                      //     delta: 1
                      //   });
                      //  }

                    } else {
                      wx.showToast({
                        title: res.data.msg,
                        duration: 1000,
                        icon: 'fail'
                      });
                    }
                  }
                }
              })
            } else if (res.cancle) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }

  },
  userlist: function() {
    var that = this;
    wx.navigateTo({
      url: "../userlist/userlist?id=" + that.data.id + "&type=4"
    });
  },
  middle: function(e) {
    const data = e.currentTarget.dataset.list;
    if (data.recType == 0) {
      wx.navigateTo({
        url: "../activedetial/activedetial?id=" + data.recOtherid

      });
    } else if (data.recType == 1) {
      wx.navigateTo({
        url: "../art/art?id=" + data.recOtherid
      });
    } else {
      wx.navigateTo({
        url: "../classdetail/classdetail?id=" + data.recOtherid
      });
    }
  },
  addCollection: function(e) {
    console.log(e)
    var that = this;
    const opeType = e.currentTarget.dataset.collection;
    const json = that.data.detial_activity;
    const n = {
      openId: getApp().globalData.wxUserInfo.openId,
      otherId: json.wsId,
      type: 3,
      opeType: opeType
    };
    if (opeType == 0) {
      n.img = json.wsImg;
      n.title = json.wsTitle;
    }
    wx.request({
      url: api.detail.add_del_Collection,
      data: n,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            const tips = opeType == 0 ? '已收藏' : '已取消';
            r.setData({
              tips: tips,
              isCollection: opeType == 0 ? 1 : 0
            })
            r.toast.showToast(tips);
          }

        }
      }
    });
  },

});